﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Event.Core;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Event.UI;
using CPPEI.Coolzon.Metadata;
using CPPEI.Coolzon.UI;
using CPPEI.Coolzon.UI.Data;
using CPPEI.Coolzon.UI.Event;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CPPEI.Coolzon.Theme.Default.MainViewControl
{
    /// <summary>
    /// ControlPanel.xaml 的交互逻辑
    /// </summary>
    public partial class ControlPanel : UserControl
    {
        private Scene scene;
        private SubSeneButton CurrentScene;
        private delegate void AsyncFreeze();
        private double _touchDownY;
        private double _touchUpY;
        private bool _isFistPre = true;


        public bool FromImmediate;
        public ControlPanel()
        {
            InitializeComponent();

            tbComments.IsReadOnly = true;
            tbComments.IsUndoEnabled = false;

            isAutoPlay.Checked += isAutoPlay_Checked;
            isMagnifier.Checked += isMagnifier_Checked;
            isMagnifier.Unchecked += isMagnifier_Unchecked;
            isPen.Checked += isPen_Checked;
            isPen.Unchecked += isPen_Unchecked;
            btnNext.TouchUp += btnNext_TouchUp;
            bttPre.TouchUp += bttPre_TouchUp;
        }

        void isMagnifier_Unchecked(object sender, RoutedEventArgs e)
        {
            UIEventBus.Publish(new UIShowLaserPointEvent(false));
            NCLEventBus.Publish(new NCLShowMagnifierEvent(false, scene.Name, 1.5d, 0, 0, 0, 0));
        }
        void isMagnifier_Checked(object sender, RoutedEventArgs e)
        {
            UIEventBus.Publish(new UIShowMagnifierEvent(true));
            isPen.IsChecked = false;
            isAutoPlay.IsChecked = false;
        }
        void isPen_Unchecked(object sender, RoutedEventArgs e)
        {
            UIEventBus.Publish(new UIShowLaserPointEvent(false));
            NCLEventBus.Publish(new NCLShowLaserPointerEvent(false, null, 0, 0, 0, 0, 0));
        }
        void isPen_Checked(object sender, RoutedEventArgs e)
        {
            UIEventBus.Publish(new UIShowLaserPointEvent(true));
            isMagnifier.IsChecked = false;
            isAutoPlay.IsChecked = false;
        }

        void bttPre_TouchUp(object sender, TouchEventArgs e)
        {
            bttPre.Style = (Style)gdLayout.Resources["SceneImageSmall"];
        }
        void btnNext_TouchUp(object sender, TouchEventArgs e)
        {
            btnNext.Style = (Style)gdLayout.Resources["SceneImageBig"];
        }
        void isAutoPlay_Checked(object sender, RoutedEventArgs e)
        {
            isPen.IsChecked = false;
            isMagnifier.IsChecked = false;
            if (UIContext.Current.Solution.Displayflow != null && UIContext.Current.Solution.Displayflow.Nodes.Count > 0)
            {
                this.Dispatcher.BeginInvoke(
                    new AsyncFreeze(delegate
                    {
                        CPPEI.Coolzon.UI.Views.AutoPlayView autoPlayView = new CPPEI.Coolzon.UI.Views.AutoPlayView();
                        UIEventBus.Register(autoPlayView);
                        NCLEventBus.Register(autoPlayView);
                        CoreEventBus.Register(autoPlayView);
                        UIContext.Current.RootViewContainer.PopView("自动播放", autoPlayView, false);
                    }));
            }
            else
            {
                isAutoPlay.IsChecked = false;
            }
        }
        /// <summary>
        /// 加载子场景
        /// </summary>
        public void BindSceneImmediate()
        {
            if (scene.Scenes == null || scene.Scenes.Count == 0) return;
            for (int index = 0; index < scene.Scenes.Count; index++)
            {
                SubSeneButton btn = new SubSeneButton();
                btn.tbNum.Text = (index + 1).ToString();
                btn.Tag = index;
                btn.DataContext = scene;
                btn.MouseLeftButtonDown += btn_MouseLeftButtonDown;
                subScene.Children.Add(btn);
            }
        }

        void btn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SubSeneButton btn = sender as SubSeneButton;
            if (btn == CurrentScene) return;

            NCLEventBus.PublishAsync(new NCLOpenSceneEvent(SwitchMode.Replace, "", (btn.DataContext as Scene).Name, null));

            btn.btnImage.Style = (Style)btn.spLayout.Resources["Press"];
            if (CurrentScene != null)
            {
                CurrentScene.btnImage.Style = (Style)CurrentScene.spLayout.Resources["NumberImageBase"];
            }
            CurrentScene = btn;
        }

        [Common.Subscribe]
        public void OnOpened(CoreOpenSceneCompletedEvent @event)
        {
            try
            {
                scene = SolutionUtil.GetScene(UIContext.Current.Solution, @event.SceneName);
                if (scene == null) return;

                if (!FromImmediate && @event.SwitchMode != SwitchMode.Pop && (@event.FrameName == null || !@event.FrameName.Equals("root")))
                {
                    BindSceneImmediate();
                }
                FromImmediate = false;

                if (scene.Scenes != null)
                {
                    for (int i = 0; i < subScene.Children.Count; i++)
                    {
                        if (subScene.Children[i] is SubSeneButton)
                        {
                            SubSeneButton btn = subScene.Children[i] as SubSeneButton;
                            if ((btn.DataContext as Scene).Name.Equals(@event.SceneName))
                            {
                                btn.btnImage.Style = (Style)btn.spLayout.Resources["Press"];
                            }
                        }
                    }
                }
                ArrayList al = UIContext.Current.Solution.GetScenePath(scene);
                for (int i = 0; i < al.Count; i++)
                {
                    Scene iScene = al[i] as Scene;
                    tbPosion.Text = scene.Caption;
                    if (i < al.Count - 1)
                    {
                        tbPosion.Text = tbPosion.Text + "-";
                    }
                }

                SetComments();

                //如果是弹出场景除显示自定义按钮外所有按钮不可用
                if (@event.SwitchMode == SwitchMode.Pop)
                {
                    SetButtonEnable(false);
                }
                else
                {
                    SetButtonEnable(true);
                }
                isMagnifier.IsChecked = false;
                isPen.IsChecked = false;
            }
            catch (Exception ex)
            {
                Logger.Error("ControlPanel-OnOpened:" + ex.Message);
            }
        }

        /// <summary>
        /// 设置按钮是否可用
        /// </summary>
        /// <param name="isEnable"></param>
        private void SetButtonEnable(bool isEnable)
        {
            bttPre.IsEnabled = isEnable;
            btnNext.IsEnabled = isEnable;
            isAutoPlay.IsEnabled = isEnable;
            isMagnifier.IsEnabled = isEnable;
            isPen.IsEnabled = isEnable;
        }

        [Subscribe]
        public void OnSceneClosed(CoreCloseSceneCompletedEvent @event)
        {
        }
        [Subscribe]
        public void StopAutoPlay(ConsoleStopAutoPlayEvent @event)
        {
            isAutoPlay.IsChecked = false;
        }
        /// <summary>
        /// 设置注释内容
        /// </summary>
        private void SetComments()
        {
            if (scene.CommentsLink != null)
            {
                string absFilePaht = SolutionResourceManager.GetAbsoluteFilePath(scene.CommentsLink.Name);
                using (StreamReader sr = new StreamReader(absFilePaht, Encoding.GetEncoding("gb2312")))
                {
                    TextRange textRangeAll = new TextRange(tbComments.Document.ContentStart, tbComments.Document.ContentEnd);
                    textRangeAll.Load(sr.BaseStream, DataFormats.Rtf);
                }
            }
            else
            {
                tbComments.Document.Blocks.Clear();
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Common.EventBus.Instance.Publish(new ShowRecordEvent());
        }

        [Common.Subscribe]
        public void AnimationBeginEvent(AnimationBeginEvent @event)
        {
            if (@event != null && @event.Name.Equals("expand") && tbComments.Document.Blocks.Count > 0)
            {
                tbComments.Document.Blocks.Clear();
            }
        }

        [Common.Subscribe]
        public void AnimationEndEvent(AnimationEndEvent @event)
        {
            if (@event != null && @event.Name.Equals("expand") && tbComments.Document.Blocks.Count == 0)
            {
                SetComments();
            }
        }
        [Common.Subscribe]
        public void SceneUpdate(CPPEI.Coolzon.UI.Views.SceneUpdateEvent @event)
        {
            scene = @event.Scene.SceneMatadata;
            if (@event.Reason == UI.Views.SceneUpdateReason.ResetScene)
            {
                isMagnifier.IsChecked = false;
                isPen.IsChecked = false;
            }
        }

        private void bttPre_Click(object sender, RoutedEventArgs e)
        {
            if (!_isFistPre)
            {
                Scene nextScene = SolutionUtil.GetPreDisplayflowNode(UIContext.Current.Solution, scene);
                if (nextScene == null) return;

                OpenSceneArgs openSceneArgs = new OpenSceneArgs();
                openSceneArgs.ParametersString.Add("sys:isresetviewstate", "true");
                NCLEventBus.PublishAsync(new NCLOpenSceneEvent(SwitchMode.Replace, "", nextScene.Name, openSceneArgs));

                btnNext.Style = (Style)gdLayout.Resources["SceneImageBig"];
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            _isFistPre = false;
            Scene nextScene = SolutionUtil.GetNextDisplayflowNode(UIContext.Current.Solution, scene);
            if (nextScene == null) return;

            OpenSceneArgs openSceneArgs = new OpenSceneArgs();
            openSceneArgs.ParametersString.Add("sys:isresetviewstate", "true");
            NCLEventBus.PublishAsync(new NCLOpenSceneEvent(SwitchMode.Replace, "", nextScene.Name, openSceneArgs));

            bttPre.Style = (Style)gdLayout.Resources["SceneImageSmall"];
        }
    }
}
